package com.szsfm.vehiclemanagement.tcp;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.PowerManager;
import android.os.SystemClock;

import com.orhanobut.logger.Logger;

import java.util.concurrent.atomic.AtomicBoolean;

public class TcpUtil {

    private static String TAG = "TcpUtil";

    /**
     * 电源管理
     */
    private static volatile PowerManager.WakeLock WAKE_LOCK = null;
    private static final String PERMISSION_WAKE_LOCK = "android.permission.WAKE_LOCK";
    private static final String WAKE_LOCK_NAME = "cn.stkj.friend.wake_lock";
    private static volatile WifiManager.WifiLock WIFI_LOCK = null;
    private static final String WIFI_LOCK_NAME = "cn.stkj.friend.wifi_lock";
    private static final String ALARM_ACTION = "cn.stkj.friend.alarm";
    private static final AtomicBoolean isRegisterAlarm = new AtomicBoolean(false);

    static void lock(Context context) {
        if (PackageManager.PERMISSION_GRANTED == context.checkCallingOrSelfPermission(PERMISSION_WAKE_LOCK)) {
            PowerManager.WakeLock wakeLock = getWakeLock(context.getApplicationContext());
            if (!wakeLock.isHeld()) {
                wakeLock.acquire();
            }
            if (!isWifi(context)) return;
            WifiManager.WifiLock wifiLock = getWifiLock(context.getApplicationContext());
            if (!wifiLock.isHeld()) {
                wifiLock.acquire();
            }
        }
    }

    static void unlock(Context context) {
        if (PackageManager.PERMISSION_GRANTED == context.checkCallingOrSelfPermission(PERMISSION_WAKE_LOCK)) {
            PowerManager.WakeLock wakeLock = getWakeLock(context.getApplicationContext());
            if (wakeLock.isHeld()) {
                wakeLock.release();
            }
            WifiManager.WifiLock wifiLock = getWifiLock(context.getApplicationContext());
            if (wifiLock.isHeld()) {
                wifiLock.release();
            }
        }
    }

    private static void registerAlarm(Context context) {
        if (isRegisterAlarm.get()) {
            return;
        }
        isRegisterAlarm.set(true);
        final Intent intent = new Intent(context, TcpReceiver.class);
        intent.setAction(ALARM_ACTION);
        final PendingIntent pending = PendingIntent.getBroadcast(context, 0, intent, 0);
        final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(pending);
        alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 15 * 60 * 1000, pending);
    }

    private static final synchronized WifiManager.WifiLock getWifiLock(Context context) {
        if (PackageManager.PERMISSION_GRANTED != context.checkCallingOrSelfPermission(PERMISSION_WAKE_LOCK)) {
            return null;
        }
        if (WIFI_LOCK == null) {
            WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WIFI_LOCK = wm.createWifiLock(WifiManager.WIFI_MODE_FULL, WIFI_LOCK_NAME);
            WIFI_LOCK.setReferenceCounted(true);
        }

        return (WIFI_LOCK);
    }

    static boolean isWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return (null != ni && ni.isAvailable() && ni.getType() == ConnectivityManager.TYPE_WIFI);
    }

    private static final synchronized PowerManager.WakeLock getWakeLock(Context context) {
        if (PackageManager.PERMISSION_GRANTED != context.checkCallingOrSelfPermission(PERMISSION_WAKE_LOCK)) {
            return null;
        }
        if (WAKE_LOCK == null) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            WAKE_LOCK = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME);
            WAKE_LOCK.setReferenceCounted(true);
        }

        return (WAKE_LOCK);
    }

    /**
     * 判断手机是否有网络
     *
     * @param context
     * @return
     */
    public static boolean hasNetwork(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return (null != ni && ni.isAvailable());
    }

    public static void startSavService(Context context) {
        Intent i = new Intent(context, TcpService.class);
        if (!hasNetwork(context)) {
            i.putExtra("noNetwork", "n");
        } else {
            i.putExtra("noNetwork", "y");
        }
        Logger.i("startSavService >" + !hasNetwork(context));
        context.startService(i);
    }

    public static void stopSavService(Context context) {
        Logger.i("stopSavService");
        Intent i = new Intent(context, TcpService.class);
        context.stopService(i);
    }

    static void onReceive(Context context, Intent intent) {
        if (null != intent && ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
            startSavService(context);
        } else {
            Logger.i(TAG, "registerAlarm");
            registerAlarm(context);
        }
    }

}
